import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpService } from '../../../service/http.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-loglist',
  templateUrl: './loglist.component.html',
  styleUrls: ['./loglist.component.css'],
})
export class LoglistComponent {
  public userId = 0;
  public pageInfo: any = {
    pageSize: 10,
    pageNum: 1,
    total: 0,
  };
  public userDetails: any = {};
  public isAdministrator = false;
  public studyInfo: any = {
    id: 0,
    content: '',
    logDate: null,
    name: '',
    comment: '',
    category: '',
    statusName:'',
    statusID:'',
  };
  public dataList: any = [];
  public showAddFlag = false;
  public showUpdateFlag = false;
  public showCommentFlag = false;

  status: any[] = [];

  constructor(
    private router: Router,
    private httpService: HttpService,
    private modalService: NzMessageService,
  ) {}

  ngOnInit() {
    const user = localStorage.getItem('user');
    if (user != null) {
      this.userDetails = JSON.parse(user);
      this.userId = Number(this.userDetails.id);
      if ('administrators' == this.userDetails.userType) {
        this.isAdministrator = true;
      }
    } else {
      this.router.navigate(['/login']);
    }

    // this.getList();
    this.loadStatus();
  }

  getList() {
    const url =
      '/rest/study?pageNum=' +
      this.pageInfo.pageNum +
      '&pageSize=' +
      this.pageInfo.pageSize;

    let data = {};
    if (this.userDetails.id != 1) {
      data = { userId: this.userDetails.id };
    }

    return this.httpService.get(url).subscribe((res: any) => {
      this.pageInfo.pageSize = res.page.pageSize;
      this.pageInfo.pageNum = res.page.pageNum;
      this.pageInfo.total = res.page.total;

      console.log('当前status字典：', this.status);
      console.log('原始日志数据：', res.data);

      this.dataList = res.data.map((item: any) => {
        console.log(this.status);
        const statusItem = this.status.find(s => String(s.id) === item.statusName);

        const name = statusItem?.statusName ?? item.statusName ?? '无数据';
        console.log(name);
        console.log('日志项：', item, '转换后状态：', name);
        return {
          ...item,
          statusName: name
        };
      });
    });
  }



  deleteConfirm(id: any) {
    const url = '/rest/study/' + id;
    return this.httpService.delete(url).subscribe((res: any) => {
      this.getList();
    });
  }

  cancel() {}

  showAdd() {
    this.router.navigate(['/addlog']);
  }

  handleCancel() {
    this.showAddFlag = false;
    this.showUpdateFlag = false;
    this.showCommentFlag = false;
  }

  handleOk() {
    const url = '/rest/study';
    if (this.studyInfo.content == null || this.studyInfo.content == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    if (this.studyInfo.name == null || this.studyInfo.name == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    if (this.studyInfo.logDate == null || this.studyInfo.logDate == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    const data = {
      content: this.studyInfo.content,
      logDate: this.studyInfo.logDate,
      name: this.studyInfo.name,
      statusName:this.studyInfo.statusName,
      statusID: this.studyInfo.statusID,
    };
    return this.httpService.post(url, data).subscribe((res: any) => {
      this.showAddFlag = false;
      this.getList();
    });
  }

  update() {
    const url = '/rest/study/update';
    if (this.studyInfo.content == null || this.studyInfo.content == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    if (this.studyInfo.name == null || this.studyInfo.name == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    if (this.studyInfo.logDate == null || this.studyInfo.logDate == '') {
      this.modalService.error('必填项不能为空！');
      return;
    }
    const data = {
      id: this.studyInfo.id,
      content: this.studyInfo.content,
      logDate: this.studyInfo.logDate,
      name: this.studyInfo.name,
      statusName: this.studyInfo.statusName,
      statusID: this.studyInfo.statusID,
    };
    return this.httpService.post(url, data).subscribe((res: any) => {
      this.showUpdateFlag = false;
      this.getList();
    });
  }

  updateStudy(id: any) {
    window.open('/updateLog?id=' + id, '_blank');
  }

  comment(id: any) {
    this.showCommentFlag = true;
    this.studyInfo.id = id;
  }

  submitComment() {
    const url = '/rest/study/comment';
    const data = {
      id: this.studyInfo.id,
      comment: this.studyInfo.comment,
    };
    return this.httpService.post(url, data).subscribe((res: any) => {
      this.showCommentFlag = false;
      this.getList();
    });
  }

  goToDetail(id: any) {
    window.open('/detailLog?id=' + id, '_blank');
  }

  loadStatus(): void {
    this.httpService.get(`/rest/status`).subscribe(
      (res: any) => {
        if (res.data && res.data.length > 0) {
          this.status = [...res.data];
          console.log('加载的状态:', this.status);

          // 状态加载完成后再加载日志列表
          this.getList();
        } else {
          this.modalService.error('获取状态数据失败!');
        }
      },
      (error) => {
        console.log('请求失败:', error);
        this.modalService.error('请求状态数据失败!');
      }
    );
  }

  statusColorMap: { [key: string]: string } = {
    '未开始': '#fa541c',  // 橘红色
    '草稿': '#8c8c8c',    // 灰色
    '进行中': '#1890ff',  // 蓝色
    '已完成': '#52c41a'   // 绿色
  };


}
